package mail

import (
	"emailcenter/utils/logx"
	"github.com/pkg/errors"
	"github.com/spf13/viper"
	"gopkg.in/gomail.v2"
	"strings"
)

type DefConf struct {
	Account  string
	Password string
	From     string
	Host     string
	Port     int
	LinkUrl  string
}

var conf *DefConf
var dialer *gomail.Dialer
var build strings.Builder

func InitMail() {
	conf = &DefConf{
		Account:  viper.GetString("email.account"),
		Password: viper.GetString("email.password"),
		From:     viper.GetString("email.from"),
		Host:     viper.GetString("email.host"),
		Port:     viper.GetInt("email.port"),
		LinkUrl:  viper.GetString("email.linkUrl"),
	}
	dialer = gomail.NewDialer(conf.Host, conf.Port, conf.Account, conf.Password)
	// 测试 sender 可用性
	testMsg := gomail.NewMessage()
	testMsg.SetHeaders(map[string][]string{
		"From":    {conf.Account},
		"To":      {conf.Account},
		"Subject": {"邮箱服务启动测试"},
	})
	err := dialer.DialAndSend(testMsg)
	if err != nil {
		logx.LogrusObj.Fatal(errors.Wrap(err, "[MAIL]"))
	}
	logx.LogrusObj.Println("[MAIL] mail sender is working")
	// 字符串缓冲大小
	build.Grow(2048)
}

func SendMailWithUUID(to, recipient, uuid string) error {
	msg := gomail.NewMessage()
	msg.SetHeaders(map[string][]string{
		"From":    {msg.FormatAddress(conf.Account, conf.From)},
		"To":      {to},
		"Subject": {"邮箱验证通知"},
	})
	build.WriteString(HtmlString11)
	build.WriteString(recipient)
	build.WriteString(HtmlString12)
	build.WriteString(to)
	build.WriteString(HtmlString13)
	build.WriteString(conf.LinkUrl)
	build.WriteString(HtmlString14)
	build.WriteString(uuid)
	build.WriteString(HtmlString15)
	msg.SetBody("text/html", build.String())
	build.Reset()
	return dialer.DialAndSend(msg)
}

func SendMailWithCaptcha(to, captcha, operate string) error {
	msg := gomail.NewMessage()
	msg.SetHeaders(map[string][]string{
		"From":    {msg.FormatAddress(conf.Account, conf.From)},
		"To":      {to},
		"Subject": {"邮箱验证码"},
	})
	build.WriteString(HtmlString21)
	build.WriteString(to)
	build.WriteString(HtmlString22)
	build.WriteString(operate)
	build.WriteString(HtmlString23)
	build.WriteString(captcha)
	build.WriteString(HtmlString24)
	msg.SetBody("text/html", build.String())
	build.Reset()
	return dialer.DialAndSend(msg)
}

// TODO 邮箱优雅化
// TODO 内容配置化
const HtmlString11 = `<style>.content {display: flex;flex-direction: row-reverse column;justify-content: flex-start;align-content: center;font-size: 14px;flex-wrap: wrap;padding: 30px;}.content>.greet {width: 100%;order: -2;}.content>.main {order: -1;padding: 10px;}.content>.tip, .content>.link {width: 100%;}.content>.link {margin-left: 30px;}.content>.with {width: 100%;padding-left: 20px;height: 24px;line-height: 24px;font-size: 10px;color: rgb(255, 0, 0);}.content>.picture {order: 2;height: 100px;margin-left: 80px;}@media screen and (max-width: 400px) {.content>.phone {margin: 0 auto;}}</style><div class="content"><img class="picture phone" src="http://47.111.152.148:30501/emailcenter/v1/nil/image/email-bak.png"><div class="greet"><strong>`
const HtmlString12 = ` 用户:</strong></div><div class="main">您正在提交对`
const HtmlString13 = `的验证，请点击以下链接完成邮箱验证，有效期为 3 分钟。</div><div class="with">（如果不是您提交的申请，请忽略）</div><div class="link"><strong>验证链接：</strong><a href="`
const HtmlString14 = `?key=`
const HtmlString15 = `">点此</a></div><div class="tip">如果以上链接无法点击，可以复制以上链接在浏览器打开。</div></div>`

const HtmlString21 = `<style>.content {display: flex;flex-direction: row-reverse column;justify-content: flex-start;align-content: center;font-size: 14px;flex-wrap: wrap;padding: 30px;}.content>.main {order: -1;padding: 10px;}.content>.tip, .content>.link {width: 100%;}.content>.link {margin-left: 30px;}.content>.with {width: 100%;padding-left: 20px;height: 24px;line-height: 24px;font-size: 10px;color: rgb(255, 0, 0);}.content>.picture {order: 2;height: 100px;margin-left: 80px;}@media screen and (max-width: 400px) {.content>.phone {margin: 0 auto;}}</style><div class="content"><img class="picture phone" src="http://47.111.152.148:30501/emailcenter/v1/nil/image/email-bak.png"><div class="main">您正在提交对`
const HtmlString22 = `的`
const HtmlString23 = `验证，验证码有效期为 3 分钟。</div><div class="with">（如果不是您发起的验证，请忽略）</div><div class="link"><strong>验证码：<a href="#">`
const HtmlString24 = `</a></strong></div><div class="tip">请勿将验证码泄露给他人。</div></div>`

func SendRemindMail(to, content string) error {
	msg := gomail.NewMessage()
	msg.SetHeaders(map[string][]string{
		"From":    {msg.FormatAddress(conf.Account, conf.From)},
		"To":      {to},
		"Subject": {"提现提醒"},
	})
	msg.SetBody("text/html", content)
	return dialer.DialAndSend(msg)
}
